# -*- coding:utf-8 -*-
import socket
import select
from threading import Thread

class Request(object):
    def __init__(self,request):
        self.request    = request
        self.host       = None
        self.port       = 80
        self.method     = 'GET'
        self.uri        = '/'
        self.lenth      = len(self.request)
        self.protocol   = 'HTTP/1.1'
        self.headers    = {}
        self.content    = None
        try:self.parse()
        except:pass

    def parse(self):
        head,self.content = self.request.split('\r\n\r\n')
        lines = head.split('\r\n')
        '''解析请求方法和uri'''
        self.method,self.uri,self.protocol = lines[0].split()
        self.method = self.method.upper()

        '''解析其他header'''
        for line in lines[1:]:
            head = line.split(':')
            self.headers[head[0]] = ':'.join(head[1:]).strip()

        '''处理目标主机和端口'''
        host_port = self.headers['Host'].split(':')
        self.host = host_port[0]
        if len(host_port)==2:
            self.port = int(host_port[1])

class Response(object):
    def __init__(self,response):
        self.response   = response
        self.lenth      = len(self.response)
        self.protocol   = 'HTTP/1.1'
        self.status     = 200
        self.message    = ''
        self.mimetype   = ''
        self.headers    = {}
        self.content    = None

    def parse(self):
        head,self.content = self.response.split('\r\n\r\n')
        lines = head.split('\r\n')
        '''解析返回状态'''
        line = lines[0].split(' ')
        self.httptype = line[0]
        self.status = int(line[1])
        self.message = line[2]
        '''解析其他header'''
        for line in lines[1:]:
            line= lines[i].split(':')
            key = line.pop(0)
            value = ''.join(line)
            self.headers[key] = value.strip()
        self.mimetype = self.headers['Content-Type']

class HttpTunnel(Thread):
    BUFFER = 8192
    def __init__(self,client,addr):
        Thread.__init__(self)
        self.addr   = addr
        self.client = client
        self.sock   = None

    def run(self):
        while True:
            buff = self.client.recv(self.BUFFER)
            if not buff:break
            req = Request(buff)
            if req.host and req.port:
                self.sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM);
                self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
                #sock.connect(('127.0.0.1',8080))#调试时候用
                self.sock.connect((req.host,req.port))
            self.sock.send(buff)
            self.doproxy()
        self.client.close()

    def doproxy(self):
        while True:
           (rlist,wlist,elist) = select.select([self.sock],[],[],3)
           if rlist:
               buff = rlist[0].recv(self.BUFFER)
               self.client.send(buff)
               if not buff:
                   self.sock.close()
                   break

class Proxy(object):
    def __init__(self,listhost='127.0.0.1',listport=6666,listen=100):
        self.listhost = listhost
        self.listport = listport
        self.listen   = listen
        self.clientsock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        self.clientsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)#不知道放这里有没有意义
        self.clientsock.bind((self.listhost,self.listport))

    def start(self):
        self.clientsock.listen(self.listen)
        print('Start HttpProxy Listen: %s:%s'%(self.listhost,self.listport))
        while True:
            client,addr = self.clientsock.accept()
            HttpTunnel(client,addr).start()

c = Proxy()
c.start()